from machine import Pin

"""
74HC595 引脚说明

15, 1~7: Q0~Q7
14: DS
11: SHCP
12: STCP
13: OE
9: Q7S
8: GND
16: VCC
"""


class Chip74HC595(object):
	def __init__(self, ds: int=4, shcp: int=0, stcp: int=2, oe: int=14):
		# 串行数据输入
		self._ds = Pin(ds, Pin.OUT, value=0)

		# 移位寄存器时钟控制
		self._shcp = Pin(shcp, Pin.OUT, value=0)

		# 数据锁存器时钟控制
		self._stcp = Pin(stcp, Pin.OUT, value=0)

		# 使能，低电平显示，高电平不显示
		self._oe = Pin(oe, Pin.OUT, value=1)

	def set_bit_data(self, data):
		self._oe.on()

		for bit in data:
			if bit == '1':
				self._ds.off()
			else:
				self._ds.on()

			self._read_bit()

		self._set_data()
		self._oe.off()

	def clear(self):
		for i in range(8):
			self._ds.off()
			self._read_bit()

		self._set_data()
		self._oe.on()

	# 拉高电平，从ds引脚读取1位数据
	def _read_bit(self):
		self._shcp.off()
		self._shcp.on()

	# 拉高电平，复制8位数据到锁存器，用于显示
	def _set_data(self):
		self._stcp.off()
		self._stcp.on()
